//
//  CHSCharacterCountTextView.m
//  ChildHoodStemp
//
//  Created by 日东 罗 on 13-9-9.
//
//

#import "CHSCharacterCountTextView.h"
#import "UIUtil.h"
#import <QuartzCore/QuartzCore.h>
#import "MicroDef.h"
#import "NSString+CBExtension.h"

#define kViewRoundedCornerRadius 6.0f
#define kMaxCharacterCount 30 //bug 8678 fixed by lixu
#define kFontName @"[z] Arista"
#define kPlaceholderText @"请输入个人签名..."

#define KNormalTextColor RGBCOLOR(0x32, 0x32, 0x32)
#define KPlacehoderTextColor RGBCOLOR(0xd4, 0xd4, 0xd4)

@interface CHSCharacterCountTextView (Private)
-(void)setupView;
@end

@implementation CHSCharacterCountTextView
@synthesize text = _text;

@synthesize delegate;

- (void)dealloc
{
//    NSLog(@"CHSCharacterCountTextView dealloc");
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        
		// Setup the view
		[self setupView];
    }
    return self;
}

//-(id)initWithCoder:(NSCoder *)aDecoder {
//	
//	if( (self = [super initWithCoder:aDecoder]) ) {
//		
//		// Setup the view
//		[self setupView];
//	}
//	return self;
//}

- (NSAttributedString *)attrText
{
    return [self.text cookEmotionStringWithFont:Font18 textColor:RGBCOLORWITH16COLOR(0x323232)];
}

- (void)setAttrText:(NSAttributedString *)attrText
{
    messageTextView.attributedText = self.attrText;
}

-(void)setText:(NSString *)text
{
    _text = [text copy];
   
    //bug 6300 fixed by 荣则兵
    messageTextView.text = text;
     [messageTextView setTextColor:KNormalTextColor];
    [self updateText:text];
    showingPlaceholder = NO;

}

- (void)updateText:(NSString *)text
{
    _text = text;
    NSInteger characterCount = self.MAXCHARACTERCOUNT - [[messageTextView text] length];
    if (characterCount >= 0) {
        [characterCountLabel setText:[NSString stringWithFormat:@"%zd", characterCount]];
    }else {
        [characterCountLabel setText:@"0"];
    }
    showingPlaceholder = NO;
    [messageTextView setTextColor:KNormalTextColor];

}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

- (void)setPlaceHoldText:(NSString *)placeHoldText
{
    _placeHoldText = [placeHoldText copy];
    messageTextView.text = placeHoldText;
    [messageTextView setTextColor:KPlacehoderTextColor];
    showingPlaceholder = YES;
}

- (void)setMAXCHARACTERCOUNT:(NSInteger)MAXCHARACTERCOUNT
{
    _MAXCHARACTERCOUNT = MAXCHARACTERCOUNT;
    [characterCountLabel setText:[NSString stringWithFormat:@"%zd", self.MAXCHARACTERCOUNT]];
}

#pragma mark - Private
-(void)setupView {
	// ****** README ********
	// Sometimes the font file name will be different than the embedded font name that the iOS system is using as it's key descriptior
	// So you'll have to print the available fonts and see which one font your looking for.
	// Print the available fonts
	//NSLog(@"Available Font Families: %@", [UIFont familyNames]);
    
	// Set rounded corners on the text view
	[self.layer setCornerRadius:kViewRoundedCornerRadius];
    
	// Set showing a placeholder by default
	showingPlaceholder = YES;
	
	// Add the text view
	messageTextView = [[UITextView alloc] initWithFrame:self.bounds];
//	[messageTextView setAutocorrectionType:UITextAutocorrectionTypeNo];
	[messageTextView setReturnKeyType:UIReturnKeyDone];
	[messageTextView.layer setCornerRadius:kViewRoundedCornerRadius];
//	[messageTextView setBackgroundColor:ClearColor];
	[messageTextView setText:kPlaceholderText];
    self.placeHoldText = kPlaceholderText;
//	[messageTextView setTextColor:[UIColor lightGrayColor]];
    [messageTextView setTextColor:KPlacehoderTextColor];
	messageTextView.delegate = self;
	[messageTextView setFont:Font14];
	[self addSubview:messageTextView];
    
    self.textFont = Font14;
	// Set the max character count
	self.MAXCHARACTERCOUNT = kMaxCharacterCount;
	
	// Add a character label
	float characterCountLabelWidth = 20.0f;
	float characterCountLabelHeight =  18.0f;
	characterCountLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.frame.size.width-characterCountLabelWidth-3, self.frame.size.height-characterCountLabelHeight, characterCountLabelWidth, characterCountLabelHeight)];
    [characterCountLabel setTextAlignment:UITextAlignmentRight];
	[characterCountLabel setFont:[UIFont systemFontOfSize:14.0f]];
	[characterCountLabel setBackgroundColor:[UIColor clearColor]];
//    characterCountLabel.textColor = [UIColor lightGrayColor];
    characterCountLabel.textColor = RGBCOLOR(0xd4, 0xd4, 0xd4);
	[characterCountLabel setText:[NSString stringWithFormat:@"%zd", self.MAXCHARACTERCOUNT]];
	[self addSubview:characterCountLabel];
   
}

- (void)setTextFont:(UIFont *)textFont
{
    _textFont = textFont;
    messageTextView.font = textFont;
    [self setPlaceHoldText:self.placeHoldText];
    [self setText:self.text];
}

-(void)setEditEnable:(BOOL)isEditEnable
{
    [messageTextView setEditable:isEditEnable];
    CGRect frame = self.bounds;
    frame.origin.x = frame.origin.x + 10;
    frame.origin.y = frame.origin.y + 10;
    frame.size.width = frame.size.width - 20;
    frame.size.height = frame.size.height - 20;
    
    messageTextView.frame = frame;
    if(!isEditEnable){
//   bug 6040 
        characterCountLabel.hidden=YES;
    }
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    float characterCountLabelWidth = 30.0f;
    float characterCountLabelHeight =  18.0f;
    characterCountLabel.frame = CGRectMake(self.frame.size.width-characterCountLabelWidth-3, self.frame.size.height-characterCountLabelHeight, characterCountLabelWidth, characterCountLabelHeight);
    messageTextView.frame = self.bounds;
    
}

#pragma mark - UITextView Delegate Methods
-(void)textViewDidBeginEditing:(UITextView *)textView {
    
	// Check if it's showing a placeholder, remove it if so
	if(showingPlaceholder) {
		[textView setText:@""];
		[textView setTextColor:KNormalTextColor];
		
		showingPlaceholder = NO;
	}
    
    if ([self.delegate respondsToSelector:@selector(characterCountTextViewDidBeginEditing:)]) {
        [self.delegate characterCountTextViewDidBeginEditing:self];
    }
}

-(void)textViewDidEndEditing:(UITextView *)textView {
    
	// Check the length and if it should add a placeholder
	if([[textView text] length] == 0) {
        [self setPlaceHoldText:self.placeHoldText];
	}
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
	// if the user clicked the return key
	if ([text isEqualToString: @"\n"]) {
		// Hide the keyboard
		[textView resignFirstResponder];
		
		// Also return if its showing a placeholder
		if(showingPlaceholder) {
			return NO;
		}
		
		// Notify the delegate
		if(delegate && [delegate respondsToSelector:@selector(characterCountTextView:postedMessage:)]) {
			[delegate characterCountTextView:self postedMessage:textView.text];
		}
        
		return NO ;
	}
	return YES ;
}

- (void)textViewDidChange:(UITextView *)textView {
    if (textView.text.length > self.MAXCHARACTERCOUNT) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            textView.text = [textView.text substringToIndex:self.MAXCHARACTERCOUNT];
            [self updateText:textView.text];
        });
    }
    if (textView.text.length <= self.MAXCHARACTERCOUNT) {
        // Update the character count
        [self updateText:textView.text];
    }
    if (delegate&&[delegate respondsToSelector:@selector(characterCountTextViewDidChanged:)]) {
        [delegate characterCountTextViewDidChanged:self];
    }
}

- (void)setSelectedRange:(NSRange)selectedRange
{
    messageTextView.selectedRange = selectedRange;
}

- (NSRange)selectedRange
{
    return [messageTextView selectedRange];
}
- (BOOL)isFirstResponder
{
    [super isFirstResponder];
    return [messageTextView isFirstResponder];
}
- (BOOL)resignFirstResponder
{
    [super resignFirstResponder];
    return [messageTextView resignFirstResponder];
}
@end
